<?php

namespace app\admin\controller;

use app\base\model\User;
use app\common\controller\AdminBase;
use think\Request;
use think\Config;

class Index extends AdminBase {
  protected $modelConfig, $modelQuestion, $modelUser;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->modelConfig = new \app\admin\model\Config();
    $this->modelQuestion = new \app\admin\model\Question();
    $this->modelUser = new User();
  }

  public function _initialize() {
    parent::_initialize();
  }

  /**
   * @return \think\response\View
   * 考试参数设置
   */

  public function index() {
    $row = $this->modelConfig->getNewest();
    $id = $row['id'] || NULL;
    $qType = config('question')['type'];

    if (!\request()->isPost()) {
      $num = range(0, 100); //考试得分数组
      $qConfig = $row ? json_decode($row['q_config'], TRUE) : NULL;

      return view('', [
        'row'     => $row,
        'qConfig' => $qConfig,
        'num'     => $num,
        'qType'   => $qType,
      ]);
    }
    $form = input('form/a', NULL);
    $result = $this->validate($form, 'Config');
    if (TRUE !== $result) {
      $this->error($result);
    }
    $qConfig = $form['q_config'];

    //计算总分
    $scoreTotal = 0;
    foreach ($qConfig as $type => $v) {
      $scoreTotal += $v['num'] * $v['score'];
    }
    if ($scoreTotal != 100) {
      $this->error('题型配比要求总分100分，当前总分为' . $scoreTotal . '分，请重新设置');
    }
    //确认考题数量
    $questions = [];
    foreach ($qConfig as $type => $v) {
      //获取各个类型中有效的题目数量
      $map = ['type'    => $type,
              'disable' => 0];
      $questions[ $type ] = $this->modelQuestion->where($map)->column('id');
      //dump($questions);
      if (count($questions[ $type ]) < $v['num']) {
        $this->error('题库中题目数量小于试卷中要求的数量，无法生成数据。' . $qType[ $type ] . count($questions[ $type ]));
      }
    }
    //
    $form['q_config'] = json_encode($qConfig);
    if (TRUE !== $result) {
      $this->error($result);
    }
    cmf_log('编辑考试参数', $id, $form);
    $this->modelConfig->editJump($form, $id, url('index'));

  }

  /**
   * @return \think\response\View
   * 设置考场最大人数
   */

  public function capacity() {
    $row = $this->modelConfig->getNewest();
    $id = $row ? $row['id'] : 0;
    if (!request()->isPost()) {

      return view('', ['row' => $row]);
    }
    $form = input('form/a', NULL);

    cmf_log('编辑考场最大人数', $id, $form['capacity']);
    $this->modelConfig->editJump($form, $id);
  }

  /**
   * @return int|\think\response\View
   * 获取补考人数
   */
  public function resit() {
    $rows = $this->modelUser->getResit();

    if (request()->isAjax()) {
      return count($rows);
    }

    return view('', ['rows' => $rows]);
  }
}